"""named popen"""
import os
import subprocess
from typing import List
import psutil

from lib.global_share import GlobalShare


class NamedPopen(subprocess.Popen):
    """named popen"""

    def __init__(self, *args, name=None, **kwargs):
        self.name = name
        super().__init__(*args, **kwargs)


def set_new_session():
    """set new session"""

    os.setsid()


def get_matching_processes(features: List[str]):
    """get matching processes"""

    all_processes = psutil.process_iter()
    matching_processes = []

    for process in all_processes:
        try:
            cmdline = process.cmdline()
            if all(any(feature in arg for arg in cmdline) for feature in features):
                matching_processes.append({"pid": process.pid, "cmdline": cmdline})
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass

    return matching_processes


def execute_in_backgroud_process(
    command: str, process_name: str = None, log_file_path: str = None
):
    """execute in background process"""

    if log_file_path:
        with open(log_file_path, "w", encoding=GlobalShare.ENCODING_UTF8) as file:
            process = NamedPopen(
                command,
                shell=True,
                preexec_fn=set_new_session,
                stdout=file,
                stderr=subprocess.STDOUT,
                name=process_name,
            )
            return process
    else:
        process = NamedPopen(
            command,
            shell=True,
            preexec_fn=set_new_session,
            name=process_name,
        )
        return process
